function BeforeSave(payload) {
  var id = Process("session.Get", "user_id");
  payload["oper_id"] = id;
  //console.log("payload==>", payload);
  payload["user_id"] = id;

  if (payload.start_date) {
    for (let key in payload) {
      if (key.startsWith('start_date.')) {
        delete payload[key];
      }
    }
    const dateString = payload.start_date.slice(0, 10);
    payload.start_date = dateString;
    //console.log("task before save payload-->", payload);
  }
  return [payload];
}

function BeforeSearch(query, page, pagesize) {
  // console.log("task before search query----1->", query, page, pagesize);
  let user_id = Process("session.Get", "user_id");
  // query.orders = [{ column: "sort", option: "asc" }];
  if (user_id != 1) {
    query.wheres.push({ column: "user_id", method: "where", value: user_id, op: "eq" })
  }
  // console.log("task before search query----2->", query, page, pagesize);
  return [query, page, pagesize];
}
function SaveB(payload) {
  //console.log("task save payload-->", payload);
  if (!payload.sku) {
    throw new Exception("请提供产品的sku!", 400);
  }
  var user_id = payload.user_id;
  var sku = payload.sku;
  var task_confs = Process("models.task_conf.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }] });
  if (!task_confs || task_confs.length < 1) {
    throw new Exception("请提供产品" + sku + "任务的设置", 400);
  }
  console.log("-------------------------------");
  let startdate = payload.start_date;
  let count = 0;
  task_confs.forEach(item => {
    let _startdatestr = getDate(startdate, item.day - 1)
    let _enddatestr = getDate(startdate, item.day)
    console.log(startdate + "" + item.sku + " " + item.day + " " + _startdatestr + " " + _enddatestr);
    let t_task = Object.assign(payload, { "start_date": _startdatestr, "end_date": _enddatestr, "desc": item.desc, "points": item.points, "task_conf_id": item.id });
    Object.assign(t_task, { "title": "第" + item.day + "天" });

    let _task = Process("models.task.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }, { "column": "user_id", "op": "=", "value": user_id }, { "column": "start_date", "op": "like", "value": _startdatestr + "%" }] });
    console.log("____task:" + _task.length);
    if (_task && _task.length > 0) {
      console.log("已经存在 sku:" + sku + " user_id:" + user_id + " start_date:" + startdate + "的任务");
    } else {
      count++;
      Process("models.task.Save", t_task);
      console.log("insert task successfully", t_task);
    }


  });
  return [count];
}

function ScanDevicesToGenTasks() {
  console.log("scan devices to gen tasks --------");
  let devices = Process("models.device.get", {
    wheres: [],
    limit: 1000000,
  });
  devices.forEach(device => {
    let currentDate = new Date(); // 获取当前时间所在周的开始日期，格式如2025-02-06
    let startDate = getMondayOfTheWeek(currentDate);
    Save({ "device_id": device.id, "user_id": device.user_id, "oper_id": device.user_id, "sku": device.sku, "start_date": startDate })
  })
}
function Save(payload) {
  console.log("task save payload-->", payload);
  if (!payload.sku) {
    throw new Exception("请提供产品的sku!", 400);
  }
  let _monday = getMondayOfTheWeek(payload.start_date);
  let _sunday = getSundayOfTheWeek(payload.start_date);
  payload.start_date = _monday;
  payload.end_date = _sunday;

  var user_id = payload.user_id;
  var sku = payload.sku;
  let count = 0;
  var task_confs = Process("models.task_conf.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }] });
  if (!task_confs || task_confs.length < 1) {
    throw new Exception("请提供产品" + sku + "任务的设置", 400);
  }
  console.log("-------------------------------");
  let item = task_confs[0];
  let t_task = Object.assign(payload, { "desc": item.desc, "points": item.points, "task_conf_id": item.id, "title": item.sku + "任务" });

  let _task = Process("models.task.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }, { "column": "user_id", "op": "=", "value": user_id }, { "column": "start_date", "op": "like", "value": payload.start_date + "%" }] });
  console.log("____task:" + _task.length);
  if (_task && _task.length > 0) {
    console.log("已经存在 sku:" + sku + " user_id:" + user_id + " start_date:" + payload.start_date + "的任务");
  } else {
    count++;
    Process("models.task.Save", t_task);
    console.log("insert task successfully", t_task);
  }
  return [count]
}

function getMondayOfTheWeek(dateString) {
  // 将日期字符串转换为Date对象
  const date = new Date(dateString);

  // 获取当前日期是星期几（0-6，0表示星期日，1表示星期一，以此类推）
  const dayOfWeek = date.getDay();
  console.log("dayOfWeek--->", dayOfWeek);
  // 计算距离星期一的日期差
  console.log("date.getDate()--->", date.getDate());
  const diff = date.getDate() - dayOfWeek + 1;
  console.log("diff--->", diff);
  // 设置日期为星期一
  date.setDate(diff);

  // 格式化日期为YYYY-MM-DD格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  const day = String(date.getDate()).padStart(2, '0');

  // 返回格式化后的日期字符串
  return `${year}-${month}-${day}`;
}

function getSundayOfTheWeek(dateString) {
  // 将日期字符串转换为Date对象
  const date = new Date(dateString);
  // 获取当前日期是星期几（0-6，0表示星期日，1表示星期一，以此类推）
  let dayOfWeek = date.getDay();
  // 计算距离星期一的日期差
  if (dayOfWeek == 0) {
    dayOfWeek = 7;
  }
  const diff = date.getDate() + (7 - dayOfWeek);
  // 设置日期为星期一
  date.setDate(diff);
  // 格式化日期为YYYY-MM-DD格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  const day = String(date.getDate()).padStart(2, '0');
  // 返回格式化后的日期字符串
  return `${year}-${month}-${day}`;
}


// deprecated
function Save_day(payload) {
  //console.log("task save payload-->", payload);
  if (!payload.sku) {
    throw new Exception("请提供产品的sku!", 400);
  }
  var user_id = payload.user_id;
  var sku = payload.sku;
  var task_confs = Process("models.task_conf.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }] });
  if (!task_confs || task_confs.length < 1) {
    throw new Exception("请提供产品" + sku + "任务的设置", 400);
  }
  console.log("-------------------------------");
  let startdate = payload.start_date;
  let count = 0;
  task_confs.forEach(item => {
    let _startdatestr = getDate(startdate, item.day - 1)
    let _enddatestr = getDate(startdate, item.day)
    console.log(startdate + "" + item.sku + " " + item.day + " " + _startdatestr + " " + _enddatestr);
    let t_task = Object.assign(payload, { "start_date": _startdatestr, "end_date": _enddatestr, "desc": item.desc, "points": item.points, "task_conf_id": item.id });
    Object.assign(t_task, { "title": "第" + item.day + "天" });

    let _task = Process("models.task.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }, { "column": "user_id", "op": "=", "value": user_id }, { "column": "start_date", "op": "like", "value": _startdatestr + "%" }] });
    console.log("____task:" + _task.length);
    if (_task && _task.length > 0) {
      console.log("已经存在 sku:" + sku + " user_id:" + user_id + " start_date:" + startdate + "的任务");
    } else {
      count++;
      Process("models.task.Save", t_task);
      console.log("insert task successfully", t_task);
    }


  });
  return [count];
}

function complete(payload) {

  console.log("-------------------------------", payload);

  let _task = Process("models.task.Find", payload.id, {});
  console.log("-------------------------------", _task);
  let ret = Process("models.task.Save", payload);
  console.log("insert task successfully");

  let _integral = Process("models.integral.Get", { wheres: [{ column: "desc", value: "%:25", op: "like" }] });
  console.log("-------------------------------", _integral);
  // 取出desc 中的任务id
  if (_integral.length == 0 && _task.points > 0) {
    //  javascript 获取当前系统时间， 格式为 2025-01-07 08:01:05
    var earn_time = new Date().Format("yyyy-MM-dd HH:mm:ss");
    let integral_payload = {
      user_id: _task.user_id,
      points: _task.points,
      source: "task",
      earn_time: earn_time,
      status: "normal",
      desc: "完成任务:" + _task.id,
    }
    console.log("integral_payload-->", integral_payload);
    let integral_res = Process("models.integral.save", integral_payload);
    console.log("integral_res-->", integral_res);
  }

  return [ret];
}

function OnChange(query) {
  console.log("query-OnChange----->", query)
  // 进入onchange事件
  query = query || {};
  // field = query.key;
  // newVal = query.value;
  // oldVal = query.old;
  // params = query.params; // 开发者定义数据

  var device = Process("models.device.Find", query.value, {});
  console.log("query-device----->", device)
  let data = { sku: device.sku, user_id: device.user_id };
  // console.log("query-isOnLoad----->", query.isOnLoad);

  console.log("query-data----->", data)
  return { data };
}

function getDate(dateString, daysToAdd) {
  // 转换为 Date 对象
  const dateObj = new Date(dateString);
  // 添加天数
  dateObj.setDate(dateObj.getDate() + daysToAdd);
  // 格式化输出结果
  const resultDate = dateObj.toISOString().slice(0, 10);
  // console.log("{{", dateString, resultDate, "}}");
  return resultDate;
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function taskNotiPush(payload) {
  console.log("taskNotiPush----->", payload)

  let tasks = Process("models.task.Get", {
    wheres: [
      { column: "send_status", op: "eq", value: "pending" },
      //  { column: "status", value: "启用" },
    ],
    limit: 50,
  });
  tasks.forEach(function (task) {
    console.log("task----->", task)
    let user = Process("models.admin.user.Find", task.user_id, {
      select: ["id", "name", "email", "mobile", "idcard"],
    });
    console.log("user----->", user)
    if (user["idcard"] != "") {
      console.log("user----->", user.id + " push notification!")
      Process("plugins.noti.push", user["idcard"], "task alert", task.title, task.desc)
    }

    // then update send_status to completed
    Process("models.task.Update", task.id, {
      send_status: "completed",
    })
  })

  return [tasks.length];
}